/*
 * @Author: boyyang
 * @Date: 2022-01-04 16:33:04
 * @LastEditTime: 2022-02-23 17:50:17
 * @LastEditors: boyyang
 * @Description: 筛选符合条件的路由
 * @FilePath: \boyyang\src\utils\getAsyncRoutes.ts
 */

import type { RouteRecordRaw } from 'vue-router'

const getAsyncRoutes = (asyncRoutes: RouteRecordRaw[], roles: string[]): RouteRecordRaw[] => {
    let permissionRoutes = [] as RouteRecordRaw[]
    getAsyncRoutesHelp(asyncRoutes, roles, permissionRoutes)

    return permissionRoutes
}

// 递归处理
const getAsyncRoutesHelp = (asyncRoutes: RouteRecordRaw[], roles: string[], permissionRoutes: RouteRecordRaw[]) => {
    asyncRoutes.forEach((item) => {
        if (isPermission(item, roles)) {
            permissionRoutes.push(item)
        }
        
        if (item.children) {
            getAsyncRoutesHelp(item.children, roles, permissionRoutes)
        }
    })
}

// 判断当前路由使用有权限
const isPermission = (route: RouteRecordRaw, rules: string[]): boolean => {
    const { meta } = route
    const { roles } = meta || {}

    if (!roles) return true
    return rules.some((item) => (roles as string[]).includes(item))
}

export {
    getAsyncRoutes
}
